//
//  NewsViewController.m
//  bApp
//
//  Created by Guglielmo Buzzelli on 15/05/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "NewsViewController.h"

@interface NewsViewController ()

@end

@implementation NewsViewController
@synthesize newsView;
@synthesize tableView;


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    UIImageView *backgroundImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"back_ground_app@2x.png"]];
    
    [self.view addSubview:backgroundImage ];
    [self.view sendSubviewToBack:backgroundImage ];
    
    NSTimer *mytimer = [NSTimer timerWithTimeInterval:10.0 target:self selector:@selector(start) userInfo:nil repeats:YES];
    
    tableView.backgroundColor = [UIColor clearColor];
    tableView.rowHeight =100;
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    [[NSRunLoop mainRunLoop] addTimer:mytimer forMode:NSDefaultRunLoopMode];
    
    [self start];
}


-(void)getData:(NSData *) data{
    
    NSError *error;
    
    if(data!=nil)
        json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error ];
    
    [self.tableView reloadData];
    
    
    
    
}

-(void) start{
    
    NSURL *url = [NSURL URLWithString:kGETUrl];
    
    NSData *data = [NSData dataWithContentsOfURL:url];
    
    [self getData:data];

    
}



-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return [json count];
    
}

-(UITableViewCell *)tableView:(UITableView *)tblView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tblView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    //if(cell==nil){
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
    
    NSDictionary *info = [json objectAtIndex:indexPath.row];
    
/*inizio set colori personalizzati da assegnare */ 
    CGFloat dataRed=217.0/255.0;
    CGFloat dataBlue=154/255.0;
    CGFloat dataGreen=236.0/255.0;
    UIColor *dataColor=[[UIColor alloc]initWithRed:dataRed green:dataGreen blue:dataBlue alpha:1];
    
    CGFloat rowRed=118/255.0;
    CGFloat rowBlue=46/255.0;
    CGFloat rowGreen=139/255.0;
    UIColor *rowColor=[[UIColor alloc]initWithRed:rowRed green:rowGreen blue:rowBlue alpha:1];
/*fine set colori personalizzati da assegnare */ 

/*Inizio formattazione datetime ricevuto da MYSQL(json) nella forma 
            "giorno numgiorno mese anno - ore hh:mm */
    NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *newstr = [NSString stringWithFormat:@"%@",[info objectForKey:@"data_inserimento"]];
    NSDate* sourceDate = [formatter dateFromString:newstr];
    
    NSString *dateStr;
    [formatter setDateFormat:@"EEEE d MMMM YYYY - 'ore' HH:mm"];
    [formatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"it_IT"]];
    dateStr = [formatter stringFromDate:sourceDate];  
/*Fine formattazione data*/
    
    UILabel *dateLabel = [[UILabel alloc] initWithFrame:CGRectMake(60, 8, 240, 10)];
    dateLabel.text = dateStr;
    dateLabel.backgroundColor = [UIColor clearColor];
    dateLabel.textColor = dataColor;
    dateLabel.font = [UIFont boldSystemFontOfSize:10];
    
    UILabel *rowLabel = [[UILabel alloc] initWithFrame:CGRectMake(60, 20, 240, 14)];
    rowLabel.text = [info objectForKey:@"title"];
    rowLabel.backgroundColor = [UIColor clearColor];
    rowLabel.textColor = [UIColor whiteColor];
    rowLabel.shadowOffset = CGSizeMake(0, 1);
    rowLabel.font = [UIFont boldSystemFontOfSize:13];
    
    UILabel *rowDetailLabel = [[UILabel alloc] initWithFrame:CGRectMake(60, 35, 240, 50)];
    rowDetailLabel.text = [info objectForKey:@"message"];
    rowDetailLabel.backgroundColor = [UIColor clearColor];
    rowDetailLabel.textColor = [UIColor whiteColor];
    rowDetailLabel.font = [UIFont boldSystemFontOfSize:12];
    rowDetailLabel.numberOfLines = 3;

    
    UILabel *rowNumberLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 35, 25, 25)];
    rowNumberLabel.text =[NSString stringWithFormat:@"%d",indexPath.row+1];
    rowNumberLabel.backgroundColor = [UIColor clearColor];
    rowNumberLabel.textColor = rowColor;
    rowNumberLabel.font = [UIFont boldSystemFontOfSize:13];
    rowNumberLabel.textAlignment = UITextAlignmentCenter;
    
    
    [cell.contentView addSubview:dateLabel];
    [cell.contentView addSubview:rowLabel];
    [cell.contentView addSubview:rowDetailLabel];
    [cell.contentView addSubview:rowNumberLabel];
    //}  
    
/*Inizio setting background delle celle. Per la prima cella
  setto il background selected
 */    
    UIImage *rowBackground;
    UIImage *selectionBackground;
    
    if(indexPath.row == 0){

        rowBackground = [UIImage imageNamed:@"box_news_select@2x.png"];  
    }else{
        rowBackground = [UIImage imageNamed:@"box_news_unselect@2x.png"];  
    }
    selectionBackground = [UIImage imageNamed:@"box_news_select@2x.png"];
    
    cell.backgroundView = [[UIImageView alloc] initWithImage:rowBackground];
    cell.selectedBackgroundView = [[UIImageView alloc] initWithImage:selectionBackground];
/*Fine setting background celle*/    
    
    return cell;
    
}

-(NSString *)getNewNews:(NSString *)newDate{
    

    oldFistDate = nil;
    [self start];
    NSDictionary *info = [json objectAtIndex:0];
    
    if(newDate!=nil){
        
        if (![newDate isEqualToString:[info objectForKey:@"data_inserimento"]]) {
            
            NSLog(@"vecchia:%@ | attuale:%@",newDate,[info objectForKey:@"data_inserimento"]);                
            
            newDate = [info objectForKey:@"data_inserimento"];
            
            UILocalNotification *notifica = [[UILocalNotification alloc] init];
            
            NSDate *startDate = [[NSDate date] dateByAddingTimeInterval:30];
            
            [notifica setFireDate:startDate];
            [notifica setAlertBody:@"Ci sono novità da Sasseo!"];
            [notifica setAlertAction:@"Scopri le novità"];
            
            [[UIApplication sharedApplication] scheduleLocalNotification:notifica ];
            [[UIApplication sharedApplication] setApplicationIconBadgeNumber:1];

            
        }else{
            //[[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
        }
        
    }else{
        newDate = [info objectForKey:@"data_inserimento"];  
        //[[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
    }
    

    
    return newDate;
}



- (void)viewDidUnload
{
    [self setNewsView:nil];
    [self setTableView:nil];
    [super viewDidUnload];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

@end
